package com.xuecheng.content.service.impl;

import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson.JSON;
import com.xuecheng.basic.api.BasicClient;
import com.xuecheng.commons.constants.CourseConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.vo.CategoryVo;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.model.vo.TeachplanVo;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.content.config.MinioTemplate;
import com.xuecheng.content.domain.CourseBase;
import com.xuecheng.content.domain.CoursePub;
import com.xuecheng.content.mapper.CoursePubMapper;
import com.xuecheng.content.service.CourseBaseService;
import com.xuecheng.content.service.CoursePubService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.content.service.PubPageService;
import com.xuecheng.content.service.TeachplanService;
import com.xuecheng.web.exception.BusinessException;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import sun.nio.ch.IOUtil;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 课程发布 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-07-30
 */
@Service
public class CoursePubServiceImpl extends ServiceImpl<CoursePubMapper, CoursePub> implements CoursePubService {

    @Autowired
    private TeachplanService teachplanService;

    @Autowired
    private CourseBaseService courseBaseService;

    @Autowired
    private BasicClient basicClient;

    // 课程预览
    @Override
    public Map preview(Long courseBaseId) {
        // 1.课程计划
        ResponseResult<TeachplanVo> responseResult = teachplanService.treeNodes(courseBaseId);
        TeachplanVo teachplanVo = responseResult.getData();

        // 2.课程发布
        // 2-1 设置课程基本信息
        CourseBase courseBase = courseBaseService.getById(courseBaseId);
        CoursePub coursePub = BeanHelper.copyProperties(courseBase, CoursePub.class);
        // 2-2 设置课程分类名（mt：大分类、st：小分类）
        String mtName = findByCategoryName(coursePub.getMt());
        coursePub.setMtName(mtName);
        String stName = findByCategoryName(coursePub.getSt());
        coursePub.setStName(stName);
        // 2-3 课程计划json格式
        coursePub.setTeachplan(JSON.toJSONString(teachplanVo));
        // 2-4 教师信息（实战）
        // 2-5 收费规则 和 价格
        coursePub.setPrice(courseBase.getPrice().longValue());
        // 3.填充模型并返回
        Map model = new HashMap();
        model.put("teachplanNode", teachplanVo);
        model.put("coursePub", coursePub);
        return model;
    }



    @Autowired
    private PubPageService pubPageService;


    @Autowired
    private RabbitTemplate rabbitTemplate;

    // 保存课程发布
    @Override
    @Transactional
    public ResponseResult saveCoursePub(Long courseBaseId) throws IOException, TemplateException {
        // 1.查询课程基本信息
        CourseBase courseBase = courseBaseService.getById(courseBaseId);
        // 2.校验状态
        String auditStatus = courseBase.getAuditStatus();
        if (!auditStatus.equals(CourseConstants.AUDIT_PASTED_STATUS)) { // 如果不是审核通过
            throw new BusinessException(ErrorCode.PARAMSERROR);
        }
        // 3.查询coursePub
        Map map = this.preview(courseBaseId);
        // 包括：课程基本信息、课程分类名称、课程计划  （课程id  = 发布id）
        CoursePub coursePub = (CoursePub) map.get("coursePub");
        // 再设置一次课程id
        coursePub.setCourseId(courseBaseId);

        // 4.保存或更新 coursePub
        this.saveOrUpdate(coursePub);

        // 制造bug
        // int i = 1/0;

        // 5.修改课程状态
        courseBase.setAuditStatus(CourseConstants.AUDIT_PUBLISHED_STATUS);
        courseBaseService.updateById(courseBase);

        System.out.println("用户请求线程："+Thread.currentThread().getId());

        // 6.调用多线程技术，生成html，保存minio
        pubPageService.pubPage(map, coursePub.getId());


        // 7. 发送mq消息
        rabbitTemplate.convertAndSend("content-exchange","course.pub" , coursePub.getId());

        // 返回ok
        return ResponseResult.okResult();
    }

    // 根据分类id查询名称
    private String findByCategoryName(String mt) {
        ResponseResult<CategoryVo> response = basicClient.findById(mt);
        CategoryVo categoryVo = response.getData();
        String categoryVoName = categoryVo.getName();
        return categoryVoName;

    }
}
